// 获取传入的值的类型
const getValueType = (value) => {
  const type = Object.prototype.toString.call(value)
  return type.slice(8, -1)
}

export const useStorage = () => {
  const setStorage = (key, value) => {
    const valueType = getValueType(value)
	uni.setStorageSync(key, JSON.stringify({ type: valueType, value }));
  }

  const getStorage = (key) => {
	const value = uni.getStorageSync(key)
    if (value) {
      const { value: val } = JSON.parse(value)
      return val
    } else {
      return value
    }
  }

  const removeStorage = (key) => {
	uni.removeStorageSync(key);
  }

  const clear = (excludes=[]) => {
    // 获取排除项
    const keys = Object.keys(uni.getStorageInfoSync())
    const defaultExcludes = ['dynamicRouter', 'serverDynamicRouter']
    const excludesArr = excludes ? [...excludes, ...defaultExcludes] : defaultExcludes
    const excludesKeys = excludesArr ? keys.filter((key) => !excludesArr.includes(key)) : keys
    // 排除项不清除
    excludesKeys.forEach((key) => {
      uni.removeStorageSync(key);
    })
    // uni.clearStorageSync();
  }

  const setCache = (key, value, exp = 1) => {
    const obj = { exp: new Date().getTime() + exp * 1000 * 60 * 60, value: value }
	uni.setStorageSync(key, JSON.stringify(obj));
  }

  const getCache = (key) => {
    let resValue
    try {
      const value = JSON.parse(uni.getStorageSync(key))
      if (value.exp > new Date().getTime()) {
        resValue = value.value
      } else {
        uni.removeStorageSync(key);
        resValue = false
      }
    } catch (error) {
      resValue = false
    }
    return resValue
  }

  return {
    setStorage,
    getStorage,
    removeStorage,
    clear,
    setCache,
    getCache
  }
}
